<template>
	<view class="user-container">
		<!-- 用户头像和昵称 -->
		<view class="user-info" @click="showLogin=true">
			<text class="user-nickname">欢迎您！</text>
			<text class="user-nickname">{{ username }}</text>
		</view>
		<!-- 功能列表 -->
		<view class="function-list">
			<view class="function-item" @click="navigateToOptionManagement">
				<text>选项管理</text>
			</view>
			<view class="function-item">
				<text>统计信息</text>
			</view>
			<!-- 可根据需要添加更多功能项 -->
		</view>
		<!-- 登录弹窗 -->
		<u-popup mode="center" :show="showLogin" :closeOnClickOverlay="true" @close="showLogin=false">
			<view class="login-dialog">
				<input v-model="loginUsername" placeholder="请输入用户名" />
				<input v-model="loginPassword" type="password" placeholder="请输入密码" />
				<u-button @click="handleLogin" size="small" style="width: 80px">登录</u-button>
			</view>
		</u-popup>
	</view>
</template>

<script>
import user from '@/api/user.js'
export default {
	data() {
		return {
			username: '请登录',
			loginUsername: '',
			loginPassword: '',
			showLogin: false,
		};
	},
	mounted() {
		let that = this;
		let token = uni.getStorageSync('token');
		if (token) {
			user.get_username().then((res) => {
				this.username = res.username;
			}).catch((res) => {
				// console.log(res);
				that.username = '请登录';
			})
		}
	},
	methods: {
		handleLogin() {
			let data = {
				"username": this.loginUsername,
				"password": this.loginPassword
			}
			user.login(data).then((res) => {
				uni.setStorageSync('token', res.token);
				this.showLogin = false;
				this.username = this.loginUsername;
				uni.showToast({
					title: '登录成功',
					icon: 'success'
				});
			}).catch((res) => {
				console.log(res);
				uni.showToast({
					title: '登录失败，请检查用户名和密码',
					icon: 'none'
				});
			})
		},
		// 跳转到选项管理页面
		navigateToOptionManagement() {
			uni.navigateTo({
				url: '/pages/options/optionManager'
			});
		}
	}
};
</script>

<style scoped>
.user-container {
	padding: 20px;
}

.user-info {
	display: flex;
	justify-content: center;
	margin-bottom: 20px;
}

.user-avatar {
	width: 80px;
	height: 80px;
	border-radius: 50%;
	margin-right: 20px;
}

.user-nickname {
	font-size: 20px;
	font-weight: bold;
	display: flex;
	justify-content: center;
}

.function-list {
	border-top: 1px solid #eee;
}

.function-item {
	padding: 15px 0;
	border-bottom: 1px solid #eee;
	font-size: 16px;
}

.login-dialog {
	display: flex;
	flex-direction: column;
	padding: 20px;
}

.login-dialog input {
	margin-bottom: 10px;
	padding: 10px;
	border: 1px solid #ccc;
	border-radius: 4px;
}

.login-dialog button {
	margin-top: 10px;
	padding: 10px;
	border: none;
	border-radius: 4px;
	background-color: #007aff;
	color: white;
	cursor: pointer;
}
</style>